//
//  FTImageSrcollView.m
//  Decathlon
//
//  Created on 14-1-19.
//  Copyright (c) 2014年. All rights reserved.
//

#import "FTImageScrollView.h"
#import "NSString+Utils.h"
#import "RCSRotatingCircle.h"

#define DefaultViewMarign 85
#define DefaultScale  5.0
#define PROGRESSTAG   200
#define FootViewHeight  91

#define ProgressViewHeight          2
#define ProgressViewWidth         254

@implementation FTImageScrollView

-(void)dealloc
{
    _defaultImageView = nil;
    _defaultView = nil;
    self.imageView = nil;
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTap) object:nil];
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(doubleTap) object:nil];
    
    self.imgSclDelegate = nil;
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        self.delegate = self;
		self.minimumZoomScale = 1.0;
		self.maximumZoomScale = DefaultScale;
		self.showsHorizontalScrollIndicator = NO;
		self.showsVerticalScrollIndicator = NO;
		self.decelerationRate = UIScrollViewDecelerationRateFast;
		self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        
        _imageView  = [[UIImageView alloc] initWithFrame:frame];
        [_imageView setContentMode:UIViewContentModeScaleAspectFit];
        
		[self addSubview:_imageView];
        
        self.backgroundColor = [UIColor clearColor];
        
		[self initDefaultImage];
	
	    _isFinishLoading = YES;
    }
    
    return self;
}

-(void)initDefaultImage
{
	//调整发送失败图标显示位置
	CGRect rect = self.bounds;
	int defaultViewWidth = self.frame.size.width - DefaultViewMarign * 2;
	_defaultView = [[UIImageView alloc] initWithFrame:CGRectMake((rect.size.width - defaultViewWidth) / 2,
																 (rect.size.height - defaultViewWidth) / 2,
																 defaultViewWidth,
																 defaultViewWidth)];
	UIImage *image = [UIImage imageNamed:@"msg_content_bj_Default_Picture.png"];
	_defaultView.image = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
	[self addSubview:_defaultView];

	
	
	
//    int defaultViewWidth = self.frame.size.width-DefaultViewMarign*2;
//    _defaultView = [[UIImageView alloc] initWithFrame:CGRectMake(DefaultViewMarign, DefaultViewMarign+64, defaultViewWidth, defaultViewWidth)];
//    UIImage *image = [RCSFontManage imageNamed:@"msg_content_bj_Default_Picture.png"];
//    _defaultView.image = [image stretchableImageWithLeftCapWidth:5 topCapHeight:5];
//    [self addSubview:_defaultView];
	
    _defaultImageView = [[UIImageView alloc] initWithFrame:CGRectMake((defaultViewWidth - 55) / 2,
																	  (defaultViewWidth - 41) / 2,
																	  55,
																	  41)];
    [_defaultView addSubview:_defaultImageView];
	_defaultView.hidden = YES;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    if ([self isZoomed] == NO && CGRectEqualToRect([self bounds], [_imageView frame]) == NO) {
        [_imageView setFrame:[self bounds]];
    }
}

-(void)loadImage:(UIImage *)image
{
    _defaultView.hidden = YES;
    
//    CGSize imgSize = image.size;
//    
//    if (imgSize.width < self.frame.size.width && imgSize.height < self.frame.size.height) {
//        
//        float xSpace = (self.frame.size.width - image.size.width)/2;
//        float ySpace = (self.frame.size.height - image.size.height)/2;
//        
//        CGRect imgFrame = self.imageView.frame;
//        imgFrame.size = imgSize;
//        imgFrame.origin.x = xSpace;
//        imgFrame.origin.y = ySpace;
//        
//        self.imageView.frame = imgFrame;
//        
//    }else{
//        
//        self.imageView.frame = self.frame;
//    }
    
    [self.imageView setImage:image];
}

-(void)loadDefaultImage:(BOOL)bFailed
{
    _defaultView.hidden = NO;
    if (bFailed)
    {
        _defaultImageView.image = [UIImage imageNamed:@"message_picture_detial_default_failed.png"];
    }
    else
    {
        _defaultImageView.image = [UIImage imageNamed:@"message_picture_detial_default_normal.png"];
    }
    _isFinishLoading = NO;
}

-(void)setCanScrollEnabled:(BOOL)bEnabled
{
    [self setScrollEnabled:bEnabled];
    
    if(bEnabled == YES)
    {
        [_imageView setContentMode:UIViewContentModeScaleAspectFit];
        
    }
    else
    {
        [_imageView setContentMode:UIViewContentModeCenter];
    }
}


- (BOOL)isZoomed
{
    return !([self zoomScale] == [self minimumZoomScale]);
}


- (CGRect)zoomRectForScale:(float)scale withCenter:(CGPoint)center
{
    CGRect zoomRect;
    
    // the zoom rect is in the content view's coordinates.
    //    At a zoom scale of 1.0, it would be the size of the imageScrollView's bounds.
    //    As the zoom scale decreases, so more content is visible, the size of the rect grows.
    zoomRect.size.height = [self frame].size.height / scale;
    zoomRect.size.width  = [self frame].size.width  / scale;
    
    // choose an origin so as to get the right center.
    zoomRect.origin.x    = center.x - (zoomRect.size.width  / 2.0);
    zoomRect.origin.y    = center.y - (zoomRect.size.height / 2.0);
    
    return zoomRect;
}


- (void)zoomToLocation:(CGPoint)location
{
    float newScale;
    CGRect zoomRect;
    if ([self isZoomed]) {
        zoomRect = [self bounds];
    } else {
        newScale = [self maximumZoomScale];
        zoomRect = [self zoomRectForScale:newScale withCenter:location];
    }
    
    [self zoomToRect:zoomRect animated:YES];
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
	if (_isFinishLoading == YES)
	{
	    return _imageView;
	}
	return nil;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(float)scale
{
    //[[Statistics getInstance] setStatisticsDicttionary:@"506010034" type:numberCount];
	CGFloat zs = scrollView.zoomScale;
	zs = MAX(zs, 1.0);
	zs = MIN(zs, DefaultScale);
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.2];
	scrollView.zoomScale = zs;
	[UIView commitAnimations];
}

-(void)singleTap
{
    if(self.imgSclDelegate && [self.imgSclDelegate respondsToSelector:@selector(singleTap:)])
    {
        [self.imgSclDelegate singleTap:self];
    }
}

-(void)doubleTap
{
    if(self.imgSclDelegate && [self.imgSclDelegate respondsToSelector:@selector(doubleTap:)])
    {
        [self.imgSclDelegate doubleTap:self];
    }
}


-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    UITouch *touch = [[event allTouches] anyObject];
    
    NSTimeInterval delaytime = 0.3;//自己根据需要调整,不能比scrollViewDidEndZooming设置的动画时间少
    
    if ([touch tapCount] == 2)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTap) object:nil];
        [self performSelector:@selector(doubleTap) withObject:nil afterDelay:delaytime];
    }
    
    if ([touch tapCount] == 1)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTap) object:nil];
        [self performSelector:@selector(singleTap) withObject:nil afterDelay:delaytime];
    }
}


@end

@implementation FTChatImageScrollView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initProgressView];
    }
    return self;
}

-(void)initProgressView
{
    CGRect rect = self.bounds;//[[UIScreen mainScreen] bounds];
    _footView = [[UIView alloc] initWithFrame:CGRectMake(0, rect.size.height - FootViewHeight,rect.size.width , FootViewHeight)];
    _footView.backgroundColor = [UIColor clearColor];
    _footView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    
    //白色
    UIView *unDoneView = [[UIView alloc]initWithFrame:CGRectMake((self.frame.size.width-ProgressViewWidth)/2,
                                                                 0,
                                                                 ProgressViewWidth,
                                                                 ProgressViewHeight)];
    
    unDoneView.backgroundColor = [UIColor whiteColor];
    [_footView addSubview:unDoneView];
    
    //绿的
    _progressView = [[UIView alloc]init];
    _progressView.backgroundColor = RGB(31, 214, 1);
    [unDoneView addSubview:_progressView];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(rect.size.width/2 - 75, 30, 150, 14)];
    lable.backgroundColor = [UIColor clearColor];
    lable.text = @"正在下载图片";
    lable.textAlignment = NSTextAlignmentCenter;
    lable.font = [UIFont systemFontOfSize:14.0];
    lable.textColor = RGB(102, 102, 102);
    [_footView addSubview:lable];
    
    _progressLable = [[UILabel alloc] initWithFrame:CGRectMake(rect.size.width/2 - 75, lable.frame.size.height+30+2, 150, 30)];
    _progressLable.backgroundColor = [UIColor clearColor];
    _progressLable.textAlignment = NSTextAlignmentCenter;
    _progressLable.textColor = RGB(255, 255, 255);
    _progressLable.font = [UIFont systemFontOfSize:14.0];
    _progressLable.tag = PROGRESSTAG;
    [_footView addSubview:_progressLable];
    
    _footView.hidden = YES;
    [self addSubview:_footView];
}

- (void)updatePressWithFileSize:(float)fileSize AndFinishedBytes:(float)finishedBytes
{
    _footView.hidden = NO;
    _progressLable.text = [NSString stringWithFormat:@"%@ / %@", [NSString getSizeString:finishedBytes], [NSString getSizeString:fileSize]];
    float nProgress = finishedBytes*1.0/fileSize;
    int doneLen = ProgressViewWidth*nProgress;
    _progressView.frame = CGRectMake(0,
                                     0,
                                     doneLen,
                                     ProgressViewHeight);
    

}

- (void)setHiddenFootView:(BOOL)bHide
{
    _footView.hidden = bHide;
}

//是否可以双击
- (BOOL)canDoubleTap
{
    if (!_defaultView.hidden || !_footView.hidden) {
        return NO;
    }
    
    return YES;
}

- (void)handleMaxZoomScale:(BOOL)bZoom
{
    if (bZoom) {
        self.maximumZoomScale = DefaultScale;
    }
    else
    {
        self.maximumZoomScale = 1.0;
    }
}

- (void)dealloc
{
    _progressView = nil;
    _footView = nil;
    _progressLable = nil;
}

@end

#define RotatingCircleWidth       30
#define ProgressLabelHeight       15
#define ProgressLabelMarginUP     15

@interface RCSChatImageScrollView ()
{
//    UIScrollView*   _maskView;  // 蒙板view
    RCSRotatingCircle *_rotatingCircle;
    UILabel*  _progressLabel; // 进度
}
@end

@implementation RCSChatImageScrollView


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
	
    }
    return self;
}

-(void)dealloc
{    
    _progressLabel = nil;
    _rotatingCircle = nil;
}

-(void)loadProgressView
{
    CGRect rect = self.bounds;//[[UIScreen mainScreen] bounds];
    
//    // 蒙板
//    if (!_maskView)
//    {
//        _maskView = [[UIScrollView alloc] initWithFrame:self.frame];
//        _maskView.userInteractionEnabled = YES;
//        _maskView.alpha = 0.8;
//        _maskView.delegate = self;
//        _maskView.backgroundColor = RGB(46, 50, 58);
//        [self addSubview:_maskView];
//    }
    
    
    if (!_rotatingCircle)
    {
        _rotatingCircle = [[RCSRotatingCircle alloc]initWithFrame:CGRectMake((rect.size.width-RotatingCircleWidth)/2, (rect.size.height-RotatingCircleWidth-ProgressLabelMarginUP-ProgressLabelHeight)/2, RotatingCircleWidth, RotatingCircleWidth) imageName:@"message_icon_word_loading"];
        [self addSubview:_rotatingCircle];
    }
    
    if (!_progressLabel)
    {
        // 进度
        _progressLabel = [[UILabel alloc] initWithFrame:CGRectMake((rect.size.width-200)/2, _rotatingCircle.frame.origin.y+RotatingCircleWidth+ProgressLabelMarginUP, 200, ProgressLabelHeight)];
        _progressLabel.backgroundColor = [UIColor clearColor];
        _progressLabel.textAlignment = NSTextAlignmentCenter;
        _progressLabel.textColor = RGB(255, 255, 255);
        _progressLabel.font = [UIFont systemFontOfSize:15];

        [self addSubview:_progressLabel];
    }
	
	_isFinishLoading = NO;
}

-(void)setProgressPicTransSize:(NSString *)picTransSize andPicTotalSize:(NSString *)picTotalSize
{
    _progressLabel.text = [NSString stringWithFormat:@"%@ / %@", picTransSize, picTotalSize];
}

-(void)removeProgressView
{
//    if (_maskView)
//    {
//        [_maskView removeFromSuperview];
//        _maskView = nil;
//    }
    
    if (_rotatingCircle)
    {
        [_rotatingCircle removeFromSuperview];
        _rotatingCircle = nil;
    }
    
    if (_progressLabel)
    {
        [_progressLabel removeFromSuperview];
        _progressLabel = nil;
    }
	
	_isFinishLoading = YES;
}
@end


